package com.blackfish.common.plugin.aio.client.handler;

import com.blackfish.common.untils.FileUntil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import com.blackfish.common.plugin.aio.common.ShowcasePacket;
import com.blackfish.common.plugin.aio.common.intf.AbsShowcaseBsHandler;
import com.blackfish.common.plugin.aio.common.packets.P2PRespBody;
import org.tio.utils.json.Json;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author tanyaowu
 * 2017年3月27日 下午9:51:28
 */
public class P2PRespHandler extends AbsShowcaseBsHandler<P2PRespBody> {
	private static Logger log = LoggerFactory.getLogger(P2PRespHandler.class);
	public static FileUntil fileUntil = new FileUntil();

	/**
	 * @param args
	 * @author tanyaowu
	 */
	public static void main(String[] args) {

	}

	/**
	 *
	 * @author tanyaowu
	 */
	public P2PRespHandler() {
	}

	/**
	 * @return
	 * @author tanyaowu
	 */
	@Override
	public Class<P2PRespBody> bodyClass() {
		return P2PRespBody.class;
	}

	/**
	 * @param packet
	 * @param bsBody
	 * @param channelContext
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public Object handler(ShowcasePacket packet, P2PRespBody bsBody, ChannelContext channelContext) throws Exception {
		System.out.println("收到P2P响应消息:" + Json.toJson(bsBody));
		String json = bsBody.getText();
		JSONObject jsonObj = new JSONObject(json);
		String title = jsonObj.optString("name");
		String path = "F:\\Object\\Java\\jfBlackFish-web\\WebRoot\\factory\\product\\"+jsonObj.optString("path")+"\\loads";
		String write = jsonObj.optString("write");
		File file = new File(path+"\\"+title+".json");
		try {
			fileUntil.createFile(path,title+".json");
			FileWriter fileWriter = new FileWriter(file);
			fileWriter.write(write);
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}
}
